<template>
  <div class="Autocomplete">
    <group label-width="1rem" label-align="left" gutter="0">
      <x-input :title="title" @on-blur="hideAuto" @on-focus="onChange" @on-change="onChange" v-model="currentValue"
               :debounce="500" :placeholder="placeholder" :required="required"></x-input>
      <div class="container" v-if="show">
        <ul>
          <li v-for="(item,index) in list" @click="setValue(item)">{{item.mergerName}}</li>
        </ul>
      </div>
    </group>
  </div>
</template>

<script>
  import {Group, XInput, throttle, debounce} from 'vux'

  export default {
    name: "Autocomplete",
    components: {Group, XInput},
    props: {
      value: [String, Number],
      url:[String],
      title:[String],
      placeholder:[String],
      required:[String,Boolean]
    },
    created() {
      this.currentValue = this.value === undefined || this.value === null ? '' : this.value
    },
    watch: {
      value(val) {
        this.currentValue = val
      },
      currentValue(newVal, oldVal) {
        this.$emit('input', newVal);
      }
    },
    data() {
      return {
        list: [],
        currentValue: '',
        show: false,
        isSelect: '',
      }
    },
    methods: {
      onChange(newVal) {
        if (this.isSelect==newVal||newVal== undefined || newVal == null || newVal == '') {
          this.list = [];
          this.show = false;
          this.isSelect='';
          return
        }
        this.$http.get(this.url, {
          params: {
            mergerNameLike: newVal,
            include: true,
            levelSort: 'desc',
            fields: 'mergerName,level'
          }
        }).then(res => {
          if (res.data.data) {
            this.list = res.data.data.rows;
            if (this.list.length > 0)
              this.show = true;
          }
        });
      },
      // 设置值
      setValue(item) {
        this.currentValue = item.mergerName;
        this.isSelect = item.mergerName;
      },
      hideAuto() {
        this.show = false;
      },
    }
  }
</script>

<style lang="less">
  .Autocomplete {
    .weui-cells:after {
      border-bottom: none;
    }
    .container {
      max-height: 120px;
      padding: 10px 0;
      box-sizing: border-box;
      overflow-y: auto;
      background-color: #fff;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      margin-left: 1rem;
      right: 15px;
      left: 15px;
      margin-top: -10px;
      position: fixed;
      font-size: 15px;
      z-index: 1;
      ul {

        li {
          word-wrap: break-word;
        }
      }
    }
  }
</style>
